package jcode.project.mailserver.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import jcode.project.base.Utils;
import jcode.project.mailserver.entity.HtmlEmail;
import jcode.project.mailserver.entity.Mail;
import jcode.project.mailserver.mapper.MailMapper;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static jcode.project.base.Utils.isEmpty;

@RequestMapping(value = "/mail")
@Controller
public class MailController {

    private Logger logger = LoggerFactory.getLogger(MailController.class);

    @Autowired
    private MailMapper mailMapper;

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ResponseBody
    public String send(@RequestBody HtmlEmail message, HttpServletResponse response) {
        try {
            Mail mail = new Mail();
            mail.store(message);
            mailMapper.insert(mail);

            return "ok";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setStatus(500);
            return "fail";
        }
    }

    @RequestMapping(value = "/first", method=RequestMethod.GET)
    @ResponseBody
    public HtmlEmail first() throws IOException {
        List<Mail> mails = first(1);
        return isEmpty(mails) ? null : mails.get(0).toHtmlEmail();
    }

    private List<Mail> first(int number) {
        EntityWrapper<Mail> condition = new EntityWrapper();
        condition.orderBy("id", false);
        return mailMapper.selectPage(new RowBounds(0, number), condition);
    }

    @RequestMapping(value = "/list", method=RequestMethod.GET)
    @ResponseBody
    public List<HtmlEmail> list() throws IOException {
        List<Mail> mails = first(20);
        return Utils.map(mails, e -> e.toHtmlEmail());
    }

    @RequestMapping(value = "/clear", method=RequestMethod.POST)
    @ResponseBody
    public String clear() throws IOException {
        try {
            EntityWrapper<Mail> wrapper = new EntityWrapper<Mail>();
             mailMapper.delete(wrapper);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return "fail";
        }

        return "ok";
    }


}

